import gzip

from gmssl import sm2, func, sm4
def sm4_encrypt(key, iv, data, mode=sm4.SM4_ENCRYPT):
    crypt_sm4 = sm4.CryptSM4()
    crypt_sm4.set_key(key, mode)
    if iv:
        return crypt_sm4.crypt_cbc(iv, data)
    else:
        return crypt_sm4.crypt_ecb(data)

def sm4_enc(data, key, mode):
    iv = bytearray()
    iv.append(key[-1])
    for i in range(15):
        iv.append(0xf)
    print(iv.hex(sep=' '))
    k1 = key[:16]
    print(k1.hex(sep=' '))
    k2 = key[16:32]
    print(k2.hex(sep=' '))

    k = bytearray([x ^ y for x, y in zip(k1, k2)])
    print(k.hex(sep=' '))

    r = sm4_encrypt(k, iv, data, mode)
    return r

prefix = lambda result_point : '03' if int(result_point, 16) % 2 else '02'
# SM2 公钥（PEM 格式）
key = '''04:cd:03:ca:12:8b:4f:56:c7:c7:ad:5a:a5:50:92:
2d:80:31:9c:ff:ca:fe:4f:97:b5:c4:49:e7:94:38:
eb:39:d2:41:f6:e1:cf:37:cb:48:f1:66:61:45:bb:
78:10:16:83:3c:1d:d9:8b:98:99:79:08:69:5c:87:
a3:a7:48:17:51'''.replace(':','').replace('\n','').replace('\r','')

# 定义标量（16 字节的十六进制字符串）
scalar_hex = "31313131313131313131313131313131"  # 对应字符串 "1111111111111111"

# 初始化 SM2 曲线
sm2_curve = sm2.CryptSM2(private_key=None, public_key=key)

# 将标量转换为字节
scalar_bytes = bytes.fromhex(scalar_hex)

# 计算标量与生成元点（G）的乘积
result1 = sm2_curve._kg(int.from_bytes(scalar_bytes, 'big'), sm2_curve.ecc_table['g'])
print("Result 1 (scalar * G):", prefix(result1) +result1[:64])

# 计算标量与公钥点的乘积
pubkey_point = sm2_curve._kg(int.from_bytes(scalar_bytes, 'big'), sm2_curve.public_key)
print("Result 2 (scalar * pub_key_point):", prefix(pubkey_point) +pubkey_point[:64])

deKey = prefix(pubkey_point) +pubkey_point[:64]

data = '[{"clientId":"Z5HprRgUonMDAO75z6zK2tx7","productId":"9101430221728_IOS-product","productVersion":"5.9.0.2","osVersion":"15.8.3","userId":"","did":"Z5HprRgUonMDAO75z6zK2tx7","osType":"IOS","netType":"WIFI","prisonBreak":0,"mobileBrand":"Apple","mobileModel":"iPhone 7 Plus","extInfos":{"prisonBreakFlag":"-1"}}]'
# data = '1111'
compress_data = gzip.compress(data.encode())
# 1f8b0800000000000213858e516b02311084ff8aecb3864bf43cbd37a5488388626d851691abb7d5609a0dc91d58c5ffeed65aec5bdf76663e66f6ed041b6bd055ba841c5ed3471fe6db67729387c1344b8fdde35855870c9ae00395f5e607ebcb4476da89523253bdb59e3eb56ee99d7bc1100d398653d11789501c51bcbb32153dd166b38e18aea57c97e69f27282ebe3c32c39b2c1d5637bdd4237d1d3791dc3060b1873c69c227bd1b8bc350b8efe281f716e1d79d5089965d33db91c346d698d93a728a874abb0f8a909ffef68d6cb165ba25e17c5e5d00baa77a7936010000
# 1f8b0800000000000213858e516b02311084ff8aecb3864bf43cbd37a5488388626d851691abb7d5609a0dc91d58c5ffeed65aec5bdf76663e66f6ed041b6bd055ba841c5ed3471fe6db67729387c1344b8fdde35855870c9ae00395f5e607ebcb4476da89523253bdb59e3eb56ee99d7bc1100d398653d11789501c51bcbb32153dd166b38e18aea57c97e69f27282ebe3c32c39b2c1d5637bdd4237d1d3791dc3060b1873c69c227bd1b8bc350b8efe281f716e1d79d5089965d33db91c346d698d93a728a874abb0f8a909ffef68d6cb165ba25e17c5e5d00baa77a7936010000
# compress_data = bytes.fromhex('1f8b08000000000002132d904d6e83400c85ef32eb080dc3fc911da464db2cb2abaad1008e18b5302d33a1421137e8be97e8097a9ef61e35223b7ff6b3fdeca71b3123bc5f21c4d2b733d9df486d033c9c1fd7d00713e737207be2c88eb430b906cce0914525259347aeb8145cd063592aa5b82ab2ea505645c151de7d4c6be3a9f303a813267a5fbbd77b3fe235c06806dbc386d1f560421c91186582a62c4b25c725586b3a685e4ce3db552ba4d55a30cd2d6b737bd11a24e599c879abd30bcb15ea271883f3c3dd6a9227346164d991106dc4fc611bb40e76116f267f9f5fbf3fdfc8f888713e6f27fb1a0d4e4096e5f91fc0f103d926010000')
# print(gzip.decompress(compress_data))
# print(compress_data.hex())
# compress_data = b'12345455'
gzipEncryptData = sm4_enc(compress_data, bytes.fromhex(deKey), sm4.SM4_ENCRYPT)
print(gzipEncryptData.hex().upper() == '8D 02 89 9E 37 73 C6 05 02 5A B2 43 9B E3 D6 97 0C FD 60 59 64 E8 B4 9C 68 64 D4 38 69 BA 1D 73 5D 45 31 5D 00 DC F1 49 E2 DB C5 73 D9 66 8A F4 41 87 E3 B8 79 33 35 8E 4A 33 EA 3F 54 E4 39 70 5F B0 20 33 DA F5 C8 FF AC 6B DC 96 DE 31 39 15 5E C7 D9 43 0E 58 03 81 19 B4 7A FE 24 46 51 22 ED 14 02 9B 31 C9 FF D0 D1 6B 46 85 A1 71 DB D3 DE EC 13 80 9E D3 07 67 A8 FC 0F F9 C6 8F 91 5B 11 80 6E D8 A7 7A 0D 38 96 8A AC 06 D1 9B E1 9E CD 00 C0 6D 82 13 89 37 2F 1F 36 F2 11 D3 A6 D8 FC F2 3C 80 54 A5 1B B6 E3 29 23 AA 6A 85 4B 78 5B 0F 85 D9 3F D3 A8 FA D9 73 B8 6B 60 40 6A C5 D6 78 F5 AC 5A 4D 63 AB EA 5E 4A C8 CE 77 9B 2A FE 33 A3 6C 84 59 9A 52 68 B1 DB A4 2B 15 50 45 61 5B 7B 7E 2F 0B E9 EC 6A FA D8 6B AC D0 13 BB A9 43 72 30 9C 54 2D 59 40 7D 96 BF 3A 69 CF F5'.replace(' ',''))



import requests

url = "https://mobile.12306.cn/otsmobile/app/mgs/mgw.htm"

payload = bytearray()
payload.append(3)
payload.extend((33).to_bytes(3, 'big'))
payload.extend(bytes.fromhex(prefix(result1) +result1[:64]))
payload.append(0xd)
payload.extend(len(gzipEncryptData).to_bytes(3, 'big'))
payload.extend(gzipEncryptData)

print([hex(x) for x in payload])
print((33).to_bytes(3, 'big'))
headers = {
  'User-Agent': "MTPotal/16 CFNetwork/1335.0.3.4 Darwin/21.6.0",
  'Did': "Z5HprRgUonMDAO75z6zK2tx7",
  'Platform': "IOS",
  'SignType': "sm3",
  'x-mpaas-timestamp': "PIILrnJ",
  'x-mpaas-sign': "RDIA_JAIAAAAAgVsmHiB5BgCFPFtQipvoHCl2NSdsCdlcdFiTFbppuuhkTa+3XJrWLJ1FHhE=",
  'productVersion': "10.2.3.1",
  'x-mpaas-appkey': "9101430221728_IOS",
  'Ts': "PIILrnJ",
  'appv': "5.9.0.2",
  'productId': "9101430221728_IOS",
  'x-mpaas-apdidtoken': "PR6QGoSUIOUbxuVcoOMwXWhGCnIJga6azFzg6SrCpjCXHfmRlAEAAA==",
  'uuid': "4e9e0a15-e0c5-4492-b8dc-19ae1a33272e",
  'x-mpaas-miniwua': "AQAA_g4eT2Is09KPkoN0BTxTHGanxJZkBKnU8mGbCDTx4cM4Kf40IPsRjXP8QB0cWNzNCAQcVA5vs9THi/XEapAZ5PlA75fjnDMCQY9hudUvp8E4=",
  'osm': "i",
  'WorkspaceId': "product",
  'fo': "b9c1ikgv4wbf1z5hWSodYRAGJPrDf55ziM9p7170xssTkQcCWQMa4NZlcS5C3L8PbOLe22uHMPyFXJi881ODN5u4DxqN8guOkNPocb-d6JAav52gHF-9AY_hym_gbyUGvY5raT_DKPh-uzgamvoovW75px5EAWM5o7bWjA",
  'Accept-Language': "zh-CN,zh-Hans;q=0.9",
  'BlueApdidToken': "PR6QGoSUIOUbxuVcoOMwXWhGCnIJga6azFzg6SrCpjCXHfmRlAEAAA==",
  'tk': "",
  'bbid': "EC251FD8-01E8-49E3-9404-F6D84681542D",
  'Operation-Type': "com.cars.otsmobile.newHomePage.getWeatherByStationCode",
  # 'Sign': "200d3cbd03301677840e647775b18ce34148e986ce58fe15ed7153bd06ffa7d4",
  'AppId': "9101430221728",
  'Content-Type': "application/json",
  'UniformGateway': "https://mobile.12306.cn/otsmobile/app/mgs/mgw.htm",
  'x-mgs-encryption': "1",
  'Cookie': "JSESSIONID=760B51DF563E8C49C4A38CA9176BA6F4; BIGipServernginxformobile=954466826.50215.0000; BIGipServerpool_146_232_8180=820969994.8225.0000; otsBusiness=BO+AfxzlAgptZyBu+aXHKQ$$; AlteonMobile=BV3xTD/UAQq71dwjKE31Rg$$"
}

response = requests.post(url, data=payload, headers=headers)


print(response.headers)
data = sm4_enc(response.content, bytes.fromhex(deKey), sm4.SM4_DECRYPT)
print(data)
print(gzip.decompress(data))
